package controllers

import (
	"fmt"
	"video/models"

	beego "github.com/beego/beego/v2/server/web"
)

type DemoController struct {
	beego.Controller
}

// @router /demo/hello [get]
func (d *DemoController) GetHello() {
	title := "hello world in demo"
	d.Ctx.WriteString(title)
}

// @router /user/info [get]
func (d *DemoController) UserInfo() {
	var (
		id   int
		err  error
		name string
		user models.User
	)
	id, err = d.GetInt("id")
	if err != nil {
		fmt.Println("获取id反失败")
		return
	}
	user, err = models.UserInfo(id)
	if err == nil {
		name = user.Name
	} else {
		name = ""
	}
	d.Ctx.WriteString(name)
}

// @router /sql/user/info [get]
func (d *DemoController) SqlUserInfo() {
	id, err := d.GetInt("id")
	if err != nil {
		fmt.Println(err)
	}
	var title string
	var user models.User
	user, err = models.SqlUserInfo(id)
	if err != nil {
		title = "抱歉，找不到该用户"
	} else {
		title = "用户名:" + user.Name + ",手机:" + user.Mobile
	}
	d.Ctx.WriteString(title)
}

// @router /user/save [get]
// func (d *DemoController) UserSave() {
// 	name := d.GetString("name")
// 	mobile := d.GetString("mobile")
// 	avatar := d.GetString("avatar")
// 	err := models.UserSave(name, mobile, avatar)
// 	var title string
// 	if err == nil {
// 		title = "恭喜，保存成功"
// 	} else {
// 		title = "抱歉，保存失败"
// 	}
// 	d.Ctx.WriteString(title)
// }

// @router /sql/user/save [get]
func (d *DemoController) SqlUserSave() {
	name := d.GetString("name")
	mobile := d.GetString("mobile")
	avatar := d.GetString("avatar")
	err := models.SqlUserSave(name, mobile, avatar)
	var title string
	if err == nil {
		title = "恭喜，保存成功"
	} else {
		title = "抱歉，保存失败"
	}
	d.Ctx.WriteString(title)
}

// @router /sql/user/update [get]
func (d *DemoController) SqlUserUpdate() {
	id, err := d.GetInt("id")
	if err != nil {
		fmt.Println(err)
		return
	}
	name := d.GetString("name")
	models.SqlUserUpdate(id, name)
}

// @router /sql/user/delete [get]
func (d *DemoController) SqlUserDelete() {
	id, err := d.GetInt("id")
	if err != nil {
		fmt.Println(err)
		return
	}
	models.SqlUserDelete(id)
}

func (d *DemoController) SqlUserList() {
	var users []models.User
	total, users, err := models.SqlUserList()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("total", total)
		for _, v := range users {
			fmt.Println(v.Name, v.Mobile)
		}
	}
}
